package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    /**
     * 线程池
     */
    private final ExecutorService cacheChang = Executors.newFixedThreadPool(10);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        // 解决缓存穿透
//        return cachePenetration(id);

        // 使用封装的Redis工具类里的方法解决缓存穿透
        Shop shop = cacheClient.cachePenetration(RedisConstants.CACHE_SHOP_KEY, id,
                Shop.class,
                new Function<Long, Shop>() {
                    @Override
                    public Shop apply(Long aLong) {
                        return getById(aLong);
                    }
                }, RedisConstants.CACHE_NULL_TTL,
                TimeUnit.MINUTES);

        // 使用封装的Redis工具类里的方法互斥锁解决缓存穿透

        if(shop == null){
            return Result.fail("店铺不存在");
        }else {
            return Result.ok(shop);
        }

        // 互斥锁解决缓存击穿
//        return cacheBreakdownByLock(id);

        // 逻辑过期解决缓存击穿
//        return cacheBreakdownByExpire(id);

    }

    /**
     * 逻辑过期
     */
    private Result cacheBreakdownByExpire(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;

        // 先从redis读取数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        // 判断是否存在
        if (StrUtil.isBlank(shopJson)) { // 不存在
            return Result.fail("不存在");
        }

        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject data = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();

        // 检查是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            // 未过期直接返回
            return Result.ok(shop);
        }

        // 实现缓存重建
        // 获取互斥锁 为每一个店铺添加一个锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        // 判断是否成功
        if (isLock) {
            // 成功 开启独立线程 缓存创建
            cacheChang.execute(() -> {

                try {
                    this.saveShopToRedis(id, 20L);
                } catch (RuntimeException e) {
                    throw new RuntimeException(e);
                } finally {
                    unlock(lockKey);
                }
            });

        }
        return Result.ok(shop);
    }

    /**
     * 互斥锁解决缓存击穿
     */
    private Result cacheBreakdownByLock(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;

        // 先从redis读取数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        // 判断是否存在
        if (StrUtil.isNotBlank(shopJson)) { // 存在就直接用缓存的
            Shop bean = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(bean);
        }

        // 判断是否null 就是空值 用于缓存与数据库都不存在这个数据时 让请求不进入数据库中 减轻数据库压力
        if (shopJson != null) {
            return Result.fail("店铺信息不存在！");
        }

        // 实现缓存重建
        // 获取互斥锁 为每一个店铺添加一个锁
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        try {
            boolean isLock = tryLock(lockKey);
            // 判断是否成功
            if (!isLock) {
                // 失败休眠并重试
                Thread.sleep(50);
                return cacheBreakdownByLock(id);
            }

            // 成功
            // 不存在就查数据库
            Shop shop = getById(id);

            // 模拟重建延迟
//            Thread.sleep(200);

            if (shop == null) {
                // 将空值写入redis 解决缓存穿透
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return Result.fail("当前店铺不存在");
            }

            // 将数据库的数据存入redis
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return Result.ok(shop);
        } catch (RuntimeException | InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(lockKey);
        }
    }

    /**
     * 空对象解决缓存穿透
     */
    private Result cachePenetration(Long id) {
        String key = RedisConstants.CACHE_SHOP_KEY + id;

        // 先从redis读取数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        // 判断是否存在
        if (StrUtil.isNotBlank(shopJson)) { // 存在就直接用缓存的
            Shop bean = JSONUtil.toBean(shopJson, Shop.class);
            return Result.ok(bean);
        }

        // 判断是否null 就是空值 用于缓存与数据库都不存在这个数据时 让请求不进入数据库中 减轻数据库压力
        if (shopJson != null) {
            return Result.fail("店铺信息不存在！");
        }

        // 不存在就查数据库
        Shop shop = getById(id);

        if (shop == null) {
            // 将空值写入redis 解决缓存穿透
            stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return Result.fail("当前店铺不存在");
        }

        // 将数据库的数据存入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return Result.ok(shop);
    }

    /**
     * 加锁 在redis中使用setnx 这个方法 如果当前key不存在就是返回1 并设置值 如果key存在 返回0
     */
    private boolean tryLock(String key) {
        Boolean status = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.MILLISECONDS);
        return BooleanUtil.isTrue(status);
    }

    /**
     * 释放锁
     */
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    /**
     * 逻辑过期
     */
    private void saveShopToRedis(Long id, Long expireSeconds) {
        // 查询店铺数据
        Shop byId = getById(id);

        // 封装逻辑过期类
        RedisData redisData = new RedisData();
        redisData.setData(byId);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds)); // 在当前时间加上expireSeconds秒

        // 存入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    @Transactional
    @Override
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }

        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + shop.getId());
        return null;
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 是否需要根据坐标查询
        if(x == null || y == null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }

        // 计算分页参数
        int from = (current - 1) * SystemConstants.DEFAULT_PAGE_SIZE;
        int end = current * SystemConstants.DEFAULT_PAGE_SIZE;

        // 查询redis 按照距离排序 分页
        String key = RedisConstants.SHOP_GEO_KEY + typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo() // 查询出 当前以x，y为圆形半径为5000的商铺
                .search(key,
                        GeoReference.fromCoordinate(x, y),
                        new Distance(5000),
                        RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().limit(end)
                );

        if(results == null){
            return Result.ok(Collections.emptyList());
        }

        // 解析id
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();

        if(content.size() <= from){
            return Result.ok(Collections.emptyList());
        }

        // 截取 from ~ end
        List<Long> ids = new ArrayList<>(content.size());
        Map<String,Distance> distanceMap = new HashMap<>(content.size());
        content.stream().skip(from).forEach(res->{
            // 获取店铺id
            String shopId = res.getContent().getName();
            ids.add(Long.valueOf(shopId));

            // 获取距离
            Distance distance = res.getDistance();
            distanceMap.put(shopId,distance);
        });

        // 根据id查询shop
        String join = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("order by field(id," + join + ")").list();

        for(Shop shop : shops){
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }

        return Result.ok(shops);
    }
}
